package com.hd.listener;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hd.entity.activiti.UserTaskInfo;
import com.hd.service.activiti.UserTaskInfoService;

/**
 * 用户任务监听
 * 
 * @author hzhh123 2018年7月30日下午4:30:28
 */
@Component("userTaskListener")
public class UserTaskListener implements TaskListener {
	/**
	* 
	*/
	private static final long serialVersionUID = 6820940972562051949L;
	private static final Logger logger = LoggerFactory.getLogger(UserTaskListener.class);
	@Autowired
	protected RepositoryService repositoryService;

	@Autowired
	private UserTaskInfoService userTaskInfoService;

	@Override
	public void notify(DelegateTask delegateTask) {
		String processDefinitionId = delegateTask.getProcessDefinitionId(); 
		String taskDefinitionKey = delegateTask.getTaskDefinitionKey(); 
		String objId=(String) delegateTask.getVariable("objId");
		logger.info("流程实例ID="+delegateTask.getProcessInstanceId());
		logger.info("任务ID="+delegateTask.getId());
		System.out.println("processDefinitionId="+processDefinitionId);
		System.out.println("taskDefinitionKey="+taskDefinitionKey);
		logger.info("objId={}",objId);
		//前一节点用户
		String prevUserid=(String) delegateTask.getVariable("prevUserid");
		logger.info("前一节点用户:"+prevUserid);
		try {
			UserTaskInfo task = this.userTaskInfoService.getByParams(processDefinitionId,taskDefinitionKey,objId);
				String taskType = task.getMode();
				String ids = task.getUserids();
				System.out.println(taskType);
				System.out.println(ids);
					switch (taskType) {
					case "assignee": {
						delegateTask.setAssignee(ids);
						logger.info("assignee id: " + ids);
						break;
					}
					case "candidateUser": {
						String[] userIds = ids.split(",");
						List<String> users = new ArrayList<String>();
						for (int i = 0; i < userIds.length; i++) {
							users.add(userIds[i]);
						}
						delegateTask.addCandidateUsers(users);
						logger.info("候选人审批 ids: " + ids);
						break;
					}
					case "candidateGroup": {
						String[] groupIds = ids.split(",");
						List<String> groups = new ArrayList<String>();
						for (int i = 0; i < groupIds.length; i++) {
							groups.add(groupIds[i]);
						}
						delegateTask.addCandidateGroups(groups);
						logger.info("候选组审批 ids: " + ids);
						break;
					}
				  }

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
